var aws_helpers = require("./aws_helpers")
	, TEMPLATE_ORDER_LIST = "orders"
	, FILTER_ATTRS = ["status","ship_date","ship_time","item_type","sioc","fast_track","gift_wrap","hazmat"];

// add view functions into context of mustache templates
var mixinFuncs = function(obj) {
	// the context is the current mustache template

	// status
	obj.isNew				= function() { return this.Query.status == "new" };
	obj.isAccepted	= function() { return this.Query.status == "accepted" };
	obj.isPacked		= function() { return this.Query.status == "packed" };
	obj.isCancelled	= function() { return this.Query.status == "cancelled" };

	// SIOC
	obj.isSIOC			= function() { return this.Query.sioc == "true" };
	obj.nonSIOC			= function() { return this.Query.sioc == "false" };
	obj.bothSIOC 		= function() { return this.Query.sioc == "" };

	// item type
	obj.isMulti			= function() { return this.Query.item_type == "multi" };
	obj.isSingle		= function() { return this.Query.item_type == "single" };
	obj.bothItemType= function() { return this.Query.item_type == "" };
}

// order form for GET /orders?
exports.form = function(req, res) {
	// no items
	res.render(TEMPLATE_ORDER_LIST, {Item: [], Query: req.query});
};

// order list by filters
exports.filter = function(req, res) {
	var q = {domain_name: "orders"};

	if (req.query.filter_batch_size) {	// batch size
		q["limit"] = req.query.filter_batch_size;
	}

	// select expression
	var exprParams = {};
	FILTER_ATTRS.forEach(function(i){
		if(req.query[i]) exprParams[i] = this[i];
	}, req.query);

	q["expr"] = exprParams;

	aws_helpers.Select(q, function(err, result) {

		if(err) {
			res.status(500);
			res.render(TEMPLATE_ORDER_LIST, {Err: err, Query: req.query});
		} else {
			mixinFuncs(req.query);

			res.render(TEMPLATE_ORDER_LIST,
				{Item: result.SelectResult.Item, Query: req.query});
		}
	});
}

// order list by ASIN
exports.queryASIN = function(req, res) {
	var q = {
		domain_name: "orders",
		limit: req.query.ASIN_batch_size,
		expr: {ASIN: req.query.ASIN}
	};
	aws_helpers.Select(q, function(err, result) {
		if(err) {
			res.status(500);
			res.render(TEMPLATE_ORDER_LIST, {Err: err, Query: req.query});
		} else {
			res.render(TEMPLATE_ORDER_LIST,
				{Item: result.SelectResult.Item, Query: req.query});
		}
	});
}

// valid query via filters
exports.filterValidator = function(req, res, next) {
	//console.log(req);
	// validate
	req.assert("status").isIn(["new","accepted","packed","cancelled",""]);
	if (req.query["ship_date"] != "") {
		req.assert("ship_date","Invalid date format").isDate();
	}
	if (req.query["ship_time"] != "") {
		req.assert("ship_time", "Invalid time format").is(/^(20|21|22|23|[01]\d|\d)(([:.][0-5]\d){1,2})$/);
	}
	req.assert("item_type").isIn(["multi","single",""]);
	req.assert("sioc").isIn(["true","false",""]);
	req.assert("filter_batch_size", "Size is too small").min(5);	// TODO hardcode
	req.assert("filter_batch_size", "Size is too big").max(30);

	// sanitize
	["fast_track","gift_wrap","hazmat"].forEach(function(i) {
		req.sanitize(i).toBoolean();
	});

	if(req.query["filter_batch_size"]) {
		req.sanitize("filter_batch_size").toInt();
	}

	var err = req.validationErrors();

	if (err) {
		res.status(400);
		res.render(TEMPLATE_ORDER_LIST, {Errs: err, Query: req.query});
	} else {
		next();
	}
}

// valid batch query via ASIN
exports.ASINValidator = function(req, res, next) {
	// validate
	req.assert("ASIN", "Invalid ASIN format").is(/^[0-9A-Z]{10}$/i);	// based on the def of ASIN
	req.assert("ASIN_batch_size", "Size is too small").min(5);	// TODO hardcode
	req.assert("ASIN_batch_size", "Size is too small").max(30);

	// sanitize
	req.sanitize("ASIN").trim();
	req.sanitize("ASIN_batch_size").toInt();

	var err = req.validationErrors();

	if (err) {
		res.status(400);
		res.render(TEMPLATE_ORDER_LIST, {Errs: err, Query: req.query});
	} else {
		next();
	}
}
